﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Smart
{
    public class IocRegistry
    {
        /// <summary>
        /// 容器名称
        /// </summary>
        static readonly string ContextRegistName = "Smart_App_Context";

        /// <summary>
        /// 获取注入对象
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="key"></param>
        /// <returns></returns>
        public T GetObject<T>(string key)
        {
            if (!Spring.Context.Support.ContextRegistry.IsContextRegistered(ContextRegistName))
                Initialize();
            var ctx = Spring.Context.Support.ContextRegistry.GetContext(ContextRegistName);
            return (T)ctx.GetObject(key);
        }

        /// <summary>
        /// 初始化
        /// </summary>
        /// <param name="config"></param>
        public static void Initialize(string config, bool isClear)
        {
            ///是否清空
            if (isClear)
                Spring.Context.Support.ContextRegistry.Clear();

            ///未初始化时
            if (!Spring.Context.Support.ContextRegistry.IsContextRegistered(ContextRegistName))
            {
                var ctx = new Spring.Context.Support.XmlApplicationContext(ContextRegistName, false, config);
                Spring.Context.Support.ContextRegistry.RegisterContext(ctx);
            }
        }

        /// <summary>
        /// 默认初始化
        /// </summary>
        public static void Initialize(bool isClear = false)
        {
            ///默认路径
            var defaultConfig = System.IO.Path.Combine(ConstansUtils.AppConfigFolder, "appConfig.xml");
            Initialize(defaultConfig, isClear);
        }

    }
}
